package com.lsh.oms.core.service.order;

import com.alibaba.fastjson.JSONObject;
import com.lsh.base.common.json.JsonUtils;
import com.lsh.oms.api.model.es.OrderHeadForEs;
import com.lsh.oms.core.constant.ReturnCode;
import com.lsh.oms.core.enums.OrderStatus;
import com.lsh.oms.core.enums.ShippingStatus;
import com.lsh.oms.core.enums.Valid;
import com.lsh.oms.core.exception.BusinessException;
import com.lsh.oms.core.model.order.*;
import com.lsh.oms.core.proxy.service.EsProxy;
import com.lsh.oms.core.service.other.SignOrderService;
import com.lsh.oms.core.utils.GoodsServiceUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * Project Name: lsh-oms
 *
 * @author peter
 * @date 18/6/25
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
@Slf4j
public abstract class AbstractOrderService {

    private static final String receipt_url = "/cal/index/receipt";

    private static final String return_url = "/cal/index/return";

    private static final String receipt_hg_url = "/cal/index/itemreceipt";

    @Autowired
    protected SignOrderService signOrderService;

    @Autowired
    protected EsProxy esProxy;

    @Value("${shopUrl}")
    private String shopUrl;

    @Value("${signCalUrl}")
    private String signCalUrl;

    protected CalOrderContent orderReceipt(List<Map<String, Object>> items, OrderShippingHeadWithBLOBs osh, List<OrderShippingDetail> shippingDetails, String logSign) {
        long orderCode = osh.getOrderId();
        String url = signCalUrl + receipt_url;
        try {
            JSONObject content = GoodsServiceUtils.getReceiptServiceResp(items, osh, shippingDetails, url, logSign, osh.getVenderId());
            if (content == null || StringUtils.isEmpty(content.toJSONString())) {
                log.info(logSign + " 签收 订单号" + orderCode + ",请求签收计算服务返回报文为空。");
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务返回报文为空。");
            }
            CalOrderContent calOrderContent = new CalOrderContent();
            if (!content.getString("return").startsWith("[")) {
                calOrderContent.setReturnContent(JSONObject.parseObject(content.getString("return"), CalOrderReturnContent.class));
            }
            if (!content.getString("receipt").startsWith("[")) {
                calOrderContent.setReceipt(JSONObject.parseObject(content.getString("receipt"), CalOrderReceiptContent.class));
            }
            return calOrderContent;
        } catch (Throwable e) {
            log.error(logSign + " 签收 订单号" + orderCode + ",请求签收计算服务失败。");
            log.error(e.getMessage(), e);
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务失败。");
        }

    }

//    /**
//     * @param orderReceiptItem 签收数量
//     * @param osh              发货单信息
//     * @param shippingDetails  发货详情
//     * @param logSign          唯一标识
//     * @return JSONObject
//     */
//    protected CalOrderContent orderReceiptByItem(Map<Long, BigDecimal> orderReceiptItem, OrderShippingHeadWithBLOBs osh, List<OrderShippingDetail> shippingDetails, String logSign) {
//        long orderCode = osh.getOrderId();
//        String url = signCalUrl + receipt_hg_url;
//        try {
//            JSONObject content = GoodsServiceUtils.getReceiptServiceRespByItem(orderReceiptItem, osh, shippingDetails, url, logSign, osh.getVenderId());
//            if (content == null || StringUtils.isEmpty(content.toJSONString())) {
//                log.info(logSign + " 签收 订单号" + orderCode + ",请求签收计算服务返回报文为空。");
//                throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务返回报文为空。");
//            }
//            CalOrderContent calOrderContent = new CalOrderContent();
//            if (!content.getString("return").startsWith("[")) {
//                calOrderContent.setReturnContent(JSONObject.parseObject(content.getString("return"), CalOrderReturnContent.class));
//            }
//            if (!content.getString("receipt").startsWith("[")) {
//                calOrderContent.setReceipt(JSONObject.parseObject(content.getString("receipt"), CalOrderReceiptContent.class));
//            }
//            return calOrderContent;
//        } catch (Throwable e) {
//            log.error(logSign + " 签收 订单号" + orderCode + ",请求签收计算服务失败。");
//            log.error(e.getMessage(), e);
//            throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务失败。");
//        }
//
//    }

    /**
     * @param orderRoItem     返仓数量
     * @param osh             发货单信息
     * @param shippingDetails 发货详情
     * @param logSign         唯一标识
     * @return JSONObject
     */
    @Deprecated
    protected JSONObject orderReturn(Map<Long, BigDecimal> orderRoItem, OrderShippingHeadWithBLOBs osh, List<OrderShippingDetail> shippingDetails, String logSign) {
        JSONObject content;
        long orderCode = osh.getOrderId();
        String url = signCalUrl + return_url;
        try {
            content = GoodsServiceUtils.getReceiptServiceResp(Collections.emptyList(), osh, shippingDetails, url, logSign, osh.getVenderId());
            if (content == null || StringUtils.isEmpty(content.getString("return"))) {
                log.info(logSign + " 返仓 订单号" + orderCode + ",请求签收计算服务返回报文为空。");
                throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务返回报文为空。");
            }
        } catch (Throwable e) {
            log.error(logSign + " 返仓 订单号" + orderCode + ",请求签收计算服务失败。");
            log.error(e.getMessage(), e);
            throw new BusinessException(ReturnCode.REQUEST_FAIL, "请求签收计算服务失败。");
        }

        return content;
    }

    /**
     * 通知es
     *
     * @param osh     发货单详情
     * @param logSign 唯一标识
     */
    protected void notifyEs(OrderShippingHeadWithBLOBs osh, OrderHead orderHead, String logSign, OrderStatus orderStatus, ShippingStatus shippingStatus, OrderSignHead oldSignHead) {
        Long orderCode = osh.getOrderId();

        OrderSignHead oshHead = signOrderService.getSignHeadByOrderId(orderCode, false);
        try {

            if (oshHead == null) {
                log.info("订单" + orderCode + "的签收信息为null");
                return;
            }

            oshHead.setMarketName(OrderFactory.getMarketName(orderHead));
            oshHead.setProviderId(OrderFactory.getProviderId(orderHead));
            oshHead.setHgReceiptStatus(0);
            oshHead.setFinalMoney(oshHead.getMoney());
            log.info(logSign + "ES入参新建签收单是-- " + JsonUtils.obj2Json(oshHead));
            esProxy.createIndex(oshHead, logSign);

            OrderShippingHeadWithBLOBs oshEs = new OrderShippingHeadWithBLOBs();
            oshEs.setShippingOrderId(osh.getShippingOrderId());
            oshEs.setStatus(shippingStatus.getIndex());
            log.info(logSign + "ES入参修改发货是-- " + JsonUtils.obj2Json(oshEs));
            esProxy.editIndex(oshEs, logSign);

            OrderHeadForEs ohEs = new OrderHeadForEs();
            ohEs.setOrderCode(orderCode);
            ohEs.setOrderStatus(orderStatus.getIndex());
            log.info(logSign + "ES入参修改订单是-- " + JsonUtils.obj2Json(ohEs));
            esProxy.editIndex(ohEs, logSign);

            if (oldSignHead != null && oldSignHead.getIsValid().compareTo(Valid.DISABLE.getValue()) == 0) {
                OrderSignHead orderSignHeadDB = new OrderSignHead();
                orderSignHeadDB.setReceiptOrderId(oldSignHead.getReceiptOrderId());
                orderSignHeadDB.setIsValid(0);

                esProxy.editIndex(orderSignHeadDB, logSign);
            }

        } catch (Throwable e) {
            log.info(logSign + "订单号" + orderCode + ",生成发货单同步es失败。");
            log.info(e.getMessage(), e);
        }
    }


    protected void disableOrderSignAndEs(OrderSignHead orderSignHead, String logSign) {
        OrderSignHead orderSignHeadDB = new OrderSignHead();
        orderSignHeadDB.setReceiptOrderId(orderSignHead.getReceiptOrderId());
        orderSignHeadDB.setIsValid(0);

        if (signOrderService.setValid(orderSignHeadDB, logSign)) {
            esProxy.editIndex(orderSignHeadDB, logSign);
        }

    }


}
